package com.app.milkteaapp.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.app.milkteaapp.bean.LoginGsonBean;

public class SpUtils {
    private static SharedPreferences sp;
    private static final String TAG = "SpUtils";

    /**
     * 将当前登录的user存入SharedPreferences
     * @param context 上下文
     * @param user 当前用户
     */
    public static void putUserBean(Context context, LoginGsonBean.User user) {
        if (sp == null) {
            sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = sp.edit();
        String json = GsonUtils.toJson(user);
        Log.d(TAG, "putUserBean: 当前user:"+json);
        editor.clear();
        editor.putString("user", json);
        editor.commit();
    }

    /**
     * 取出当前登录的用户
     * @param context 上下文
     * @return 返回当前登录的用户
     */
    public static LoginGsonBean.User getUserBean(Context context) {
        if (sp == null) {
            sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        }
        String string = sp.getString("user", null);
        LoginGsonBean.User user = GsonUtils.fromJson(string, LoginGsonBean.User.class);
        return user;
    }
}
